﻿using System;
using System.ComponentModel;
using System.Windows.Data;

namespace CardPlay.Client.Converters
{
    public class GroupingAction<T> : IValueConverter
    {
        private readonly string _propertyName;
        private readonly string _displayName;

        public GroupingAction(string propertyName, string displayName)
        {
            _propertyName = propertyName;
            _displayName = displayName;

            SortDirection = ListSortDirection.Ascending;
        }

        public override string ToString()
        {
            return _displayName;
        }

        public ListSortDirection SortDirection { get; set; }

        public Func<T, Type, object> GenerateGroups { get; set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return GenerateGroups != null && value is T ? GenerateGroups((T) value, targetType) : null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }

        public void Apply(CollectionViewSource source)
        {
            using (source.DeferRefresh())
            {
                source.SortDescriptions.Clear();
                source.GroupDescriptions.Clear();

                if (GenerateGroups == null) return;

                source.SortDescriptions.Add(new SortDescription(_propertyName, SortDirection));
                source.GroupDescriptions.Add(new PropertyGroupDescription(null, this));
            }
        }
    }
}